<template>
  <div style="padding: 0 15px;">
    <van-nav-bar
        title="健康档案"
        left-arrow
        right-text="保存"
        @click-left="onClickLeft"
        @click-right="onClickRight"
    />
    <el-radio-group v-model="myHealthRecord" style="margin-top: 10px;width: 100%;text-align: center">
      <el-radio-button label="基础信息"></el-radio-button>
      <el-radio-button label="健康信息"></el-radio-button>
    </el-radio-group>
    <div style="width: 100%;margin: 10px auto;">
      <el-upload
          align="left"
          class="avatar-uploader"
          style="text-align: center"
          action="http://localhost:10086/api/user/user/upload/uploadLocal"
          :show-file-list="false"
          :on-success="handleAvatarSuccess">
        <img v-if="avatarUrl" :src="avatarUrl" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </div>
    <van-action-sheet
        v-model="show1"
        :actions="actions1"
        description="请选择您的民族"
        cancel-text="取消"
        @select="onSelect1"
    />
    <van-action-sheet
        v-model="show2"
        :actions="actions2"
        description="请选择您的文化程度"
        cancel-text="取消"
        @select="onSelect2"
    />
    <van-action-sheet
        v-model="show3"
        :actions="actions3"
        description="请选择您的婚姻状况"
        cancel-text="取消"
        @select="onSelect3"
    />
    <van-action-sheet
        v-model="show4"
        :actions="actions4"
        description="请选择您的户籍类型"
        cancel-text="取消"
        @select="onSelect4"
    />
    <div v-if="myHealthRecord == '基础信息'" style="width: 100%;margin-top: 10px;">
      <van-cell-group>
        <van-field class="healthRecordBasicInfo" v-model="healthRecordBasicInfo.realName" label="真实姓名"
                   placeholder="请输入您的真实姓名" style="border-top: 1px solid #e5e5e5;"/>
        <van-field class="healthRecordBasicInfo" v-model="healthRecordBasicInfo.idCard" label="身份证号" @blur="card"
                   placeholder="请输入您的身份证号"/>
        <van-field class="healthRecordBasicInfo" v-model="healthRecordBasicInfo.phoneNumber" label="联系电话"
                   placeholder="请输入您的联系电话"/>
        <van-field class="healthRecordBasicInfo" v-model="healthRecordBasicInfo.currentAddress" label="现居地址"
                   placeholder="请输入您的现居地址"/>
        <van-field class="healthRecordBasicInfo" v-model="healthRecordBasicInfo.householdAddress" label="户籍地址"
                   placeholder="请输入您的户籍地址"/>
        <van-field class="healthRecordBasicInfo" v-model="healthRecordBasicInfo.administrativeArea" label="行政区划"
                   placeholder="请输入您的行政区划"/>
        <van-field class="healthRecordBasicInfo" v-model="healthRecordBasicInfo.gender" label="性别"
                   placeholder="请输入您的性别"/>
        <van-field v-if="healthRecordBasicInfo.birthDate" class="healthRecordBasicInfo" v-model="healthRecordBasicInfo.birthDate" label="出生日期"
                   placeholder="请输入您的出生日期">
          <template #input>
            {{ healthRecordBasicInfo.birthDate | format('yyyy-MM-dd') }}
          </template>
        </van-field>
        <van-field
            readonly
            is-link
            class="healthRecordBasicInfo"
            v-model="healthRecordBasicInfo.ethnicity"
            label="民族"
            placeholder="请选择您的民族"
            @click="show1 = true"
        />
        <van-field
            readonly
            is-link
            class="healthRecordBasicInfo"
            v-model="healthRecordBasicInfo.education"
            label="文化程度"
            placeholder="请选择您的文化程度"
            @click="show2 = true"
        />
        <van-field
            readonly
            is-link
            class="healthRecordBasicInfo"
            v-model="healthRecordBasicInfo.maritalStatus"
            label="婚姻状况"
            placeholder="请选择您的婚姻状况"
            @click="show3 = true"
        />
        <van-field class="healthRecordBasicInfo" v-model="healthRecordBasicInfo.occupation" label="职业"
                   placeholder="请输入您的职业"/>
        <van-field class="healthRecordBasicInfo" v-model="healthRecordBasicInfo.workUnit" label="工作单位"
                   placeholder="请输入您的工作单位"/>
        <van-field class="healthRecordBasicInfo" v-model="healthRecordBasicInfo.emergencyContact" label="紧急联系人"
                   placeholder="请输入您的紧急联系人"/>
        <van-field class="healthRecordBasicInfo" v-model="healthRecordBasicInfo.contactPhone" label="联系人电话"
                   placeholder="请输入您的联系人电话"/>
        <van-field
            readonly
            is-link
            class="healthRecordBasicInfo"
            v-model="healthRecordBasicInfo.householdType"
            label="户籍类型"
            placeholder="请选择您的户籍类型"
            @click="show4 = true"
        />
        <van-field class="healthRecordBasicInfo" v-model="healthRecordBasicInfo.designatedMedicalUnit"
                   label="定点医疗单位"
                   placeholder="请输入您的定点医疗单位"/>
      </van-cell-group>
    </div>
    <van-action-sheet
        v-model="show5"
        :actions="actions5"
        description="请选择您的血型"
        cancel-text="取消"
        @select="onSelect5"
    />
    <van-action-sheet
        v-model="show6"
        :actions="actions6"
        description="请选择是或否或不详"
        cancel-text="取消"
        @select="onSelect6"
    />
    <div v-if="myHealthRecord == '健康信息'" style="width: 100%;margin-top: 10px;">
      <van-cell-group>
        <van-field class="healthRecordBasicInfo" v-model="healthRecordHealthInfo.height" label="身高"
                   placeholder="请输入您的身高cm" style="border-top: 1px solid #e5e5e5;"/>
        <van-field class="healthRecordBasicInfo" v-model="healthRecordHealthInfo.weight" label="体重"
                   placeholder="请输入您的体重kg"/>
        <van-field
            readonly
            is-link
            class="healthRecordBasicInfo"
            v-model="healthRecordHealthInfo.bloodType"
            label="血型"
            placeholder="请选择您的血型"
            @click="show5 = true"
        />
        <van-field
            readonly
            is-link
            class="healthRecordBasicInfo"
            v-model="healthRecordHealthInfo.rhNegative"
            label="RH阴性"
            placeholder="请选择是或否或不详"
            @click="show6 = true"
        />
        <van-field class="healthRecordBasicInfo" v-model="healthRecordHealthInfo.allergyHistory" label="过敏史">
          <template #input>
            <el-radio v-model="healthRecordHealthInfo.allergyHistory" label="0">无</el-radio>
            <el-radio v-model="healthRecordHealthInfo.allergyHistory" label="1">有</el-radio>
          </template>
        </van-field>
        <van-field class="healthRecordBasicInfo" v-model="healthRecordHealthInfo.pastHistory" label="既往史">
          <template #input>
            <el-radio v-model="healthRecordHealthInfo.pastHistory" label="0">无</el-radio>
            <el-radio v-model="healthRecordHealthInfo.pastHistory" label="1">有</el-radio>
          </template>
        </van-field>
        <van-field class="healthRecordBasicInfo" v-model="healthRecordHealthInfo.medicalHistory" label="就诊史">
          <template #input>
            <el-radio v-model="healthRecordHealthInfo.medicalHistory" label="0">无</el-radio>
            <el-radio v-model="healthRecordHealthInfo.medicalHistory" label="1">有</el-radio>
          </template>
        </van-field>
        <van-field class="healthRecordBasicInfo" v-model="healthRecordHealthInfo.familyHistory" label="家族病史">
          <template #input>
            <el-radio v-model="healthRecordHealthInfo.familyHistory" label="0">无</el-radio>
            <el-radio v-model="healthRecordHealthInfo.familyHistory" label="1">有</el-radio>
          </template>
        </van-field>
      </van-cell-group>
    </div>
  </div>
</template>

<script>
export default {
  name: "MyHealthRecordFoundation",
  data() {
    return {
      user: {
        id: '',
        phoneNumber: '',
        password: '',
        realName: '',
        idCard: '',
        gender: '',
        birthDate: '',
        currentAddress: '',
        relationToSelf: '',
        privacyPolicyAgreed: '',
        userType: '',
        imageUrl: '',
      },
      show1: false,
      actions1: [
        {name: '汉族'},
        {name: '回族'},
        {name: '维吾尔族'},
        {name: '壮族'},
        {name: '其他少数名族'},
      ],
      show2: false,
      actions2: [
        {name: '小学'},
        {name: '初中'},
        {name: '高中/中专'},
        {name: '大专及以上'},
        {name: '不祥'},
      ],
      show3: false,
      actions3: [
        {name: '未婚'},
        {name: '已婚'},
        {name: '离异'},
        {name: '丧偶'},
        {name: '不祥'},
      ],
      show4: false,
      actions4: [
        {name: '农村'},
        {name: '城市'},
      ],
      show5: false,
      actions5: [
        {name: 'A型'},
        {name: 'B型'},
        {name: 'O型'},
        {name: 'AB型'},
        {name: '不详'},
      ],
      show6: false,
      actions6: [
        {name: '是'},
        {name: '否'},
      ],
      imageUrl: '',
      avatarUrl: '',
      myHealthRecord: '',
      healthRecordBasicInfo: {
        id: '',
        userId: '',
        realName: '',
        idCard: '',
        phoneNumber: '',
        currentAddress: '',
        householdAddress: '',
        administrativeArea: '',
        gender: '',
        birthDate: '',
        nationality: '',
        ethnicity: '',
        education: '',
        maritalStatus: '',
        occupation: '',
        workUnit: '',
        emergencyContact: '',
        contactPhone: '',
        householdType: '',
        designatedMedicalUnit: '',
      },
      healthRecordHealthInfo: {
        id: '',
        userId: '',
        height: '',
        weight: '',
        bloodType: '',
        rhNegative: '',
        allergyHistory: 0,
        pastHistory: 0,
        medicalHistory: 0,
        familyHistory: 0,
      }
    }
  },
  created() {
    const token = JSON.parse(localStorage.getItem("token"));
    if (!token) {
      this.$message.error('请先登录');
      setTimeout(() => {
        this.$router.push({name: 'login'});
      });
    }
    // 设置全局默认请求头
    this.axios.defaults.headers.common['token'] = token;
    this.myHealthRecord = '基础信息';
    this.findHealthRecordBasicInfo()
    this.findHealthRecordHealthInfo()
    this.findUserInfo()
  },
  methods: {
    card() {
      if (this.healthRecordBasicInfo.idCard.length && this.healthRecordBasicInfo.idCard.length === 18) {
        var year = this.healthRecordBasicInfo.idCard.substring(6, 10);
        var month = this.healthRecordBasicInfo.idCard.substring(10, 12);
        var day = this.healthRecordBasicInfo.idCard.substring(12, 14);
        this.healthRecordBasicInfo.birthDate = `${year}-${month}-${day}`
      }
    },
    findHealthRecordBasicInfo(){
      this.axios.get(`http://localhost:10086/api/doctor/health_record_basic_info/findHealthRecordBasicInfo`).then(res=>{
        if (res.data.code == 200) {
          this.healthRecordBasicInfo = res.data.data
        }else{
          console.log(res);
        }
      })
    },
    findHealthRecordHealthInfo(){
      this.axios.get(`http://localhost:10086/api/doctor/health_record_health_info/findHealthRecordHealthInfo`).then(res=>{
        if (res.data.code == 200) {
          this.healthRecordHealthInfo = res.data.data
          this.healthRecordHealthInfo.allergyHistory = this.healthRecordHealthInfo.allergyHistory == false ? '0' : '1'
          this.healthRecordHealthInfo.pastHistory = this.healthRecordHealthInfo.pastHistory == false? '0' : '1'
          this.healthRecordHealthInfo.medicalHistory = this.healthRecordHealthInfo.medicalHistory == false? '0' : '1'
          this.healthRecordHealthInfo.familyHistory = this.healthRecordHealthInfo.familyHistory == false? '0' : '1'
        }else{
          console.log(res);
        }
      })
    },
    onClickRight() {
      this.user.realName = this.healthRecordBasicInfo.realName
      this.user.idCard = this.healthRecordBasicInfo.idCard
      this.user.phoneNumber = this.healthRecordBasicInfo.phoneNumber
      this.user.currentAddress = this.healthRecordBasicInfo.currentAddress
      this.user.birthDate = this.healthRecordBasicInfo.birthDate
      this.user.gender = this.healthRecordBasicInfo.gender
      this.axios.post(`http://localhost:10086/api/user/user/updateUserInfo`, this.user).then(res=>{
        if (res.data.code == 200) {
          this.axios.post(`http://localhost:10086/api/doctor/health_record_basic_info/updateHealthRecordBasicInfo`, this.healthRecordBasicInfo).then(res => {
            if (res.data.code == 200) {
              this.healthRecordHealthInfo.allergyHistory = this.healthRecordHealthInfo.allergyHistory == '0' ? false : true
              this.healthRecordHealthInfo.pastHistory = this.healthRecordHealthInfo.pastHistory == '0' ? false : true
              this.healthRecordHealthInfo.medicalHistory = this.healthRecordHealthInfo.medicalHistory == '0' ? false : true
              this.healthRecordHealthInfo.familyHistory = this.healthRecordHealthInfo.familyHistory == '0'? false : true
              this.axios.post(`http://localhost:10086/api/doctor/health_record_health_info/addHealthRecordHealthInfo`, this.healthRecordHealthInfo).then(res => {
                if (res.data.code == 200) {
                  this.$message.success('保存成功');
                  setTimeout(() => {
                    this.$router.push({name: 'my'});
                  });
                } else {
                  this.$message.error('保存失败');
                }
              })
            } else {
              this.$message.error('保存失败');
            }
          })
        }else{
          this.$message.error('保存失败,手机号已被注册');
        }
      })

    },
    findUserInfo() {
      this.axios.get(`http://localhost:10086/api/user/user/findUserInfo`).then(res => {
        if (res.data.code == 200) {
          this.user = res.data.data
          this.healthRecordBasicInfo.userId = this.user.id
          this.healthRecordHealthInfo.userId = this.user.id
          // this.healthRecordBasicInfo.phoneNumber = this.user.phoneNumber
          // this.healthRecordBasicInfo.realName = this.user.realName
          // this.healthRecordBasicInfo.idCard = this.user.idCard
          // this.healthRecordBasicInfo.gender = this.user.gender
          // this.healthRecordBasicInfo.birthDate = this.user.birthDate
          // this.healthRecordBasicInfo.currentAddress = this.user.currentAddress
          this.avatarUrl = this.user.imageUrl
          console.log(this.user)
        } else {
          console.log(res);
        }
      })
    },
    onSelect1(item) {
      this.show1 = false;
      this.healthRecordBasicInfo.ethnicity = item.name;
    },
    onSelect2(item) {
      this.show2 = false;
      this.healthRecordBasicInfo.education = item.name;
    },
    onSelect3(item) {
      this.show3 = false;
      this.healthRecordBasicInfo.maritalStatus = item.name;
    },
    onSelect4(item) {
      this.show4 = false;
      this.healthRecordBasicInfo.householdType = item.name;
    },
    onSelect5(item) {
      this.show5 = false;
      this.healthRecordHealthInfo.bloodType = item.name;
    },
    onSelect6(item) {
      this.show6 = false;
      this.healthRecordHealthInfo.rhNegative = item.name;
    },
    onClickLeft() {
      this.$router.push({name: 'my'});
    },
    handleAvatarSuccess(res, file) {
      console.log(res);
      console.log(file.raw);
      this.$message.success('上传成功')
      this.avatarUrl = URL.createObjectURL(file.raw)
      this.imageUrl = res.data
    },
  },
  filters: {
    format(value, arg) {
      function dateFormat(date, format) {
        if (typeof date === "string") {
          var mts = date.match(/(\/Date\((\d+)\)\/)/);
          if (mts && mts.length >= 3) {
            date = parseInt(mts[2]);
          }
        }
        date = new Date(date);
        if (!date || date.toUTCString() == "Invalid Date") {
          return "";
        }
        var map = {
          "M": date.getMonth() + 1, //月份
          "d": date.getDate(), //日
          "h": date.getHours(), //小时
          "m": date.getMinutes(), //分
          "s": date.getSeconds(), //秒
          "q": Math.floor((date.getMonth() + 3) / 3), //季度
          "S": date.getMilliseconds() //毫秒
        };
        format = format.replace(/([yMdhmsqS])+/g, function (all, t) {
          var v = map[t];
          if (v !== undefined) {
            if (all.length > 1) {
              v = '0' + v;
              v = v.substr(v.length - 2);
            }
            return v;
          } else if (t === 'y') {
            return (date.getFullYear() + '').substr(4 - all.length);
          }
          return all;
        });
        return format;
      }

      return dateFormat(value, arg);

    }
  },
}
</script>

<style scoped>
.healthRecordBasicInfo {
  border-bottom: 1px solid #e5e5e5;
}

.avatar-uploader .el-upload {
  border: 1px dashed #000000;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  border: 1px dashed #000000;
  border-radius: 6px;

  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  border: 1px dashed #000000;
  border-radius: 6px;

  width: 100px;
  height: 100px;
  display: block;
}
</style>